package com.example.result.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.result.SemanticResultHandler;
import com.iflytek.aiui.assist.player.AIUIPlayer;
import com.iflytek.aiui.assist.player.AIUIPlayerKitVer;
import com.iflytek.aiui.assist.player.AIUIPlayer.ContentType;
import com.iflytek.aiui.assist.player.AIUIPlayer.PlayItem;
import com.iflytek.aiuidemo.constant.DemoConstant;
import com.iflytek.aiuidemo.control.VolumeManager;
import com.iflytek.aiuidemo.player.TonePlayer;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

/**
 * 音乐语义结果。
 * 
 * @author <a href="http://www.xfyun.cn">讯飞开放平台</a>
 * @date 2016年8月18日 上午10:44:36
 * 
 */
public class MusicResult extends SemanticResult {
	private final static String KEY_OPERATION = "operation";
	private final static String KEY_SEMANTIC = "semantic";
	private final static String KEY_SLOTS = "slots";
	private final static String KEY_INSTYPE = "insType";
	private final static String KEY_STATE = "used_state";
	private final static String KEY_MISMATCH = "mismatch{artist,song}";
	private final static String OPERATION_INS = "INSTRUCTION";
	private final static String INSTYPE_SLEEP = "sleep";
	
	/** 音乐播放控制命令 **/
	private final static String INSTYPE_NEXT = "next";
	private final static String INSTYPE_PAST = "past";
	private final static String INSTYPE_REPLAY = "replay";
	private final static String INSTYPE_REPEAT = "repeat";
	private final static String INSTYPE_PAUSE = "pause";
	private final static String INSTYPE_REPLAYANSWER = "replayAnswer";
	

	/** 音量控制命令 **/
	private final static String INSTYPE_VOLMAX = "volume_max";
	private final static String INSTYPE_VOLMID = "volume_mid";
	private final static String INSTYPE_VOLMIN = "volume_min";
	private final static String INSTYPE_VOLMINUS = "volume_minus";
	private final static String INSTYPE_VOLPLUS = "volume_plus";
	
	enum INSTYPE {
		NEXT,
		PAST,
		REPLAY,
		REPEAT,
		PAUSE,
		VOLMAX,
		VOLMID,
		VOLMIN,
		VOLMINUS,
		VOLPLUS,
		INSTYPE_REPLAYANSWER
	};
	
	private static Map<String, INSTYPE> insTypeMap;
	
	static {
		insTypeMap = new HashMap<String, INSTYPE>();
		insTypeMap.put(INSTYPE_NEXT, INSTYPE.NEXT);
		insTypeMap.put(INSTYPE_PAST, INSTYPE.PAST);
		insTypeMap.put(INSTYPE_REPLAY, INSTYPE.REPLAY);
		insTypeMap.put(INSTYPE_REPEAT, INSTYPE.REPEAT);
		insTypeMap.put(INSTYPE_PAUSE, INSTYPE.PAUSE);
		insTypeMap.put(INSTYPE_VOLMAX, INSTYPE.VOLMAX);
		insTypeMap.put(INSTYPE_VOLMID, INSTYPE.VOLMID);
		insTypeMap.put(INSTYPE_VOLMIN, INSTYPE.VOLMIN);
		insTypeMap.put(INSTYPE_VOLMINUS, INSTYPE.VOLMINUS);
		insTypeMap.put(INSTYPE_VOLPLUS, INSTYPE.VOLPLUS);
		insTypeMap.put(INSTYPE_REPLAYANSWER, INSTYPE.INSTYPE_REPLAYANSWER);
	}
	
	private Context mContext;
	
	private VolumeManager mVolumeManager;
	
	private int currentVolume = -1;
	
	// 用于标示是否音量增减
	private boolean isIncrease = false;
	
	public MusicResult(String service, JSONObject json) {
		super(service, json); 
	}
	
	public String getInsType() {
		String operation = null;
		try {
			operation = json.getString(KEY_OPERATION);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		
		if (OPERATION_INS.equals(operation)) {
			// 控制语义
			try {
				JSONObject semantic = json.getJSONObject(KEY_SEMANTIC);
				String insType = semantic.getJSONObject(KEY_SLOTS).getString(KEY_INSTYPE);
				
				return insType;
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		return "";
	}
	
	@Override
	public void handleResult(Context context) {
		try {
			String operation = json.getString(KEY_OPERATION);
			
			mContext = context;
			mVolumeManager = VolumeManager.getInstance(context);
			
			if (OPERATION_INS.equals(operation)) {
				// 控制命令
				JSONObject semantic = json.getJSONObject(KEY_SEMANTIC);
				String insType = semantic.getJSONObject(KEY_SLOTS).getString(KEY_INSTYPE);
				
				// 音乐控制命令包括播放、暂停、上一首、下一首、休眠等，这里只处理了休眠命令
				if (INSTYPE_SLEEP.equals(insType)) {
					// 休眠
					Intent intent = new Intent();
					intent.setAction(DemoConstant.ACTION_SLEEP);
					
					if (null != context ) {
						context.sendBroadcast(intent);
					}
					return;
				} else if (INSTYPE_NEXT.equals(insType)) {
					// 下一首
					
				} else if (INSTYPE_PAUSE.equals(insType)) {
					// 暂停
					
				}
				
				INSTYPE type = insTypeMap.get(insType);
				
				// 音量控制
				if (null != type) {
					switch (type) {
					case VOLMAX: {
						if (null != mVolumeManager) {
							mVolumeManager.setMaxVolume();
						}
					} break;
					
					case VOLMIN: {
						if (null != mVolumeManager) {
							mVolumeManager.setMinVolume();
						}
					} break;
					
					case VOLMID: {
						if (null != mVolumeManager) {
							mVolumeManager.setMidVolume();
						}
					} break;
					
					case VOLPLUS: {
						isIncrease = true;
						playPromptTone();
					} break;
					
					case VOLMINUS: {
						isIncrease = false;
						playPromptTone();
					} break;
					
					default:
						break;
					}
				}
				return;
			}
			
			JSONObject used_state = json.getJSONObject(KEY_STATE);
			String mismatch = null;
			
			if(null != used_state) {
				mismatch = used_state.optString(KEY_MISMATCH);
			}
			
			// mismatch不为空播放answer中的提示语，否则不存在此字段的时候播放音乐。、
			if (!TextUtils.isEmpty(mismatch)) {
				super.handleResult(context);
				return;
			}
			
			// 获得歌曲信息
			JSONArray results = json.getJSONObject("data").getJSONArray("result");
			JSONObject song = (JSONObject) results.get(0);
			
			if (null != song) {
				TonePlayer.playTone(mContext, DemoConstant.SEARCH_RESULT);
				
				// 歌曲播放url
				String audiopath = song.optString("audiopath");
				JSONObject answer = json.optJSONObject("answer");
				
				if (null != answer) {
					// 合成的音乐信息
					String text = answer.optString("text");
					
					if (!TextUtils.isEmpty(audiopath)) {
						// 播放合成音和音乐播放
						List<PlayItem> itemList = new ArrayList<AIUIPlayer.PlayItem>();
						itemList.add(new PlayItem(ContentType.TEXT, text, new Runnable() {
						
									@Override
									public void run() {
										try {
											Thread.sleep(1000);
										} catch (InterruptedException e) {
											e.printStackTrace();
										}
									}
								}));
						itemList.add(new PlayItem(ContentType.MUSIC, audiopath, null));
					
						AIUIPlayerKitVer player = SemanticResultHandler.getAIUIPlayer();
						if (null != player) {
							player.playItems(itemList, null);
						}
					}
				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
			
			AIUIPlayerKitVer player = SemanticResultHandler.getAIUIPlayer();
			if (null != player) {
				PlayItem item = new PlayItem(ContentType.TEXT, "音乐结果解析出错", null);
				List<PlayItem> itemList = new ArrayList<AIUIPlayer.PlayItem>();
				itemList.add(item);
				
				player.playItems(itemList, null);
			}
		}
	}

	/**
	 * 播放音量增减提示音。
	 */
	public void playPromptTone() {
		// 连续播放三次提示音
		if (null != mVolumeManager) {
			currentVolume = mVolumeManager.getCurrentVolume();
		}
		
		TonePlayer.playUseSoundPool(mContext, DemoConstant.VOLUME_CHANGE, 3);
		
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				if (null !=mVolumeManager) {
					if (isIncrease) {
						mVolumeManager.setVolume(currentVolume + 2);
					} else {
						mVolumeManager.setVolume(currentVolume - 2);
					}
				}
				
				// 连续播放三次提示音
				TonePlayer.playUseSoundPool(mContext, DemoConstant.VOLUME_CHANGE, 3);
			}
		}, 500);
	}
	
	@Override
	protected void doAfterTTS() {
		
	}

}
